package strategy

import (
	"context"
	"errors"

	"gitee.com/leonscript/sally/v2/domain/entity"
)

// ApprovalResult 审批结果
type ApprovalResult struct {
	// ShouldPass 是否应该通过节点
	ShouldPass bool
	// ShouldReject 是否应该拒绝节点
	ShouldReject bool
	// ShouldContinue 是否应该继续等待其他审批
	ShouldContinue bool
}

// ApprovalStrategyHandler 审批策略处理器接口
type ApprovalStrategyHandler interface {
	// HandleApproval 处理审批逻辑
	// currentTask: 当前审批的任务
	// allTasks: 该节点的所有审批任务
	// isPass: 当前审批是否通过
	// taskCounter: 任务计数器，用于统计已通过的任务数量
	HandleApproval(ctx context.Context, currentTask entity.NodeReviewerTask, allTasks []entity.NodeReviewerTask, isPass bool, taskCounter TaskCounter) ApprovalResult
}

// TaskCounter 任务计数器接口
// 用于解耦审批策略与具体的任务统计逻辑
type TaskCounter interface {
	// CountPassedTasks 统计已通过的任务数量（包括指定的当前任务）
	CountPassedTasks(currentTask entity.NodeReviewerTask, allTasks []entity.NodeReviewerTask, isCurrentTaskPass bool) (passedCount int, totalCount int)
}

// OrApprovalStrategy 或批策略实现
type OrApprovalStrategy struct{}

// HandleApproval 或批策略：任意一人通过即通过，任意一人拒绝即拒绝
func (o *OrApprovalStrategy) HandleApproval(ctx context.Context, currentTask entity.NodeReviewerTask, allTasks []entity.NodeReviewerTask, isPass bool, taskCounter TaskCounter) ApprovalResult {
	if isPass {
		// 或批策略下，任意一人通过即可通过整个节点
		return ApprovalResult{
			ShouldPass:     true,
			ShouldReject:   false,
			ShouldContinue: false,
		}
	} else {
		// 或批策略下，任意一人拒绝即拒绝整个节点
		return ApprovalResult{
			ShouldPass:     false,
			ShouldReject:   true,
			ShouldContinue: false,
		}
	}
}

// AndApprovalStrategy 与批策略实现
type AndApprovalStrategy struct{}

// HandleApproval 与批策略：所有人通过才能通过，任意一人拒绝即拒绝
func (a *AndApprovalStrategy) HandleApproval(ctx context.Context, currentTask entity.NodeReviewerTask, allTasks []entity.NodeReviewerTask, isPass bool, taskCounter TaskCounter) ApprovalResult {
	if !isPass {
		// 与批策略下，任意一人拒绝即拒绝整个节点
		return ApprovalResult{
			ShouldPass:     false,
			ShouldReject:   true,
			ShouldContinue: false,
		}
	}

	// 当前审批通过，使用计数器统计已通过的任务数量
	passedCount, totalCount := taskCounter.CountPassedTasks(currentTask, allTasks, true)

	if passedCount == totalCount {
		// 所有人都已通过，节点通过
		return ApprovalResult{
			ShouldPass:     true,
			ShouldReject:   false,
			ShouldContinue: false,
		}
	} else {
		// 还有人未审批，继续等待
		return ApprovalResult{
			ShouldPass:     false,
			ShouldReject:   false,
			ShouldContinue: true,
		}
	}
}

// ApprovalStrategyFactory 审批策略工厂
type ApprovalStrategyFactory struct{}

// CreateStrategy 根据策略类型创建对应的策略处理器
func (f *ApprovalStrategyFactory) CreateStrategy(strategy entity.ApprovalStrategy) (ApprovalStrategyHandler, error) {
	switch strategy {
	case entity.ApprovalStrategyOr, "":
		return &OrApprovalStrategy{}, nil
	case entity.ApprovalStrategyAnd:
		return &AndApprovalStrategy{}, nil
	default:
		return nil, errors.New("unsupported approval strategy: " + string(strategy))
	}
}
